package com.athl.netty.nio.copy;

import java.io.FileInputStream;
import java.net.InetSocketAddress;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;

/**
 * @author hl
 * @Data 2020/8/30
 */
public class NEWIOClient {

    public static void main(String[] args) throws Exception {
        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.connect(new InetSocketAddress("localhost", 5555));
        String filename = "G:\\github\\NettyPro\\src\\main\\1.txt";
        FileChannel channel = new FileInputStream(filename).getChannel();
        long startTime = System.currentTimeMillis();
        // linux 可用全部发送 windows 只能发送 8 M ,需要分段
        // TransferTo 底层使用零拷贝
        int i = (int) (channel.size() / (8 * 1024));
        if (0 != channel.size() % (8 * 1024)) {
            i += 1;
        }
        long transferTo = 0;
        for (int j = 0; j < i; j++) {
            transferTo += channel.transferTo(j * 8 * 1024, channel.size() / i, socketChannel);
        }
        long lastTime = System.currentTimeMillis();
        System.out.println("字节数=" + transferTo + ",所费时间=" + (lastTime - startTime));
        channel.close();
    }
}
